<template>
  <div class="login-container">
    <!-- 登录页头部 -->
    <div class="login-header">
      <div class="logo-container">
        <img src="@/assets/logo.png" alt="Logo" class="logo" />
        <h1 class="site-name">{{ defaultSettings.title }}</h1>
      </div>
      <div class="header-actions">
        <el-switch
          v-model="isDark"
          inline-prompt
          active-icon="Moon"
          inactive-icon="Sunny"
          @change="toggleTheme"
        />
        <lang-select class="lang-select" />
      </div>
    </div>

    <!-- 登录页内容 -->
    <div class="login-content">
      <div class="login-banner">
        <div class="banner-text">
          <h2>欢迎回来</h2>
          <p>登录您的账户以继续访问我们的服务</p>
        </div>
      </div>

      <div class="login-form-container">
        <el-form ref="loginFormRef" :model="loginFormData" :rules="loginRules" class="login-form">
          <div class="form-header">
            <h2>用户登录</h2>
            <p class="form-subtitle">请输入您的凭据</p>
          </div>

          <!-- 用户名 -->
          <el-form-item prop="username">
            <div class="input-wrapper">
              <el-icon><User /></el-icon>
              <el-input
                ref="username"
                v-model="loginFormData.username"
                :placeholder="$t('login.username')"
                name="username"
                size="large"
              />
            </div>
          </el-form-item>

          <!-- 密码 -->
          <el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
            <el-form-item prop="password">
              <div class="input-wrapper">
                <el-icon><Lock /></el-icon>
                <el-input
                  v-model="loginFormData.password"
                  :placeholder="$t('login.password')"
                  type="password"
                  name="password"
                  size="large"
                  show-password
                  @keyup="checkCapslock"
                  @keyup.enter="handleLoginSubmit"
                />
              </div>
            </el-form-item>
          </el-tooltip>

          <!-- 验证码 -->
          <el-form-item prop="captchaCode">
            <div class="input-wrapper captcha-wrapper">
              <el-icon><Key /></el-icon>
              <el-input
                v-model="loginFormData.captchaCode"
                auto-complete="off"
                size="large"
                :placeholder="$t('login.captchaCode')"
                @keyup.enter="handleLoginSubmit"
              />
              <div class="captcha-container" @click="getCaptcha">
                <el-image :src="captchaBase64" class="captcha-img" />
                <div class="captcha-overlay">
                  <el-icon><Refresh /></el-icon>
                </div>
              </div>
            </div>
          </el-form-item>

          <!--          <div class="form-options">-->
          <!--            <el-checkbox>-->
          <!--              {{ $t("login.rememberMe") }}-->
          <!--            </el-checkbox>-->

          <!--            <el-link type="primary" href="/forget-password" class="forget-link">-->
          <!--              {{ $t("login.forgetPassword") }}-->
          <!--            </el-link>-->
          <!--          </div>-->

          <!-- 登录按钮 -->
          <el-button
            :loading="loading"
            type="primary"
            size="large"
            class="login-button"
            @click.prevent="handleLoginSubmit"
          >
            {{ $t("login.login") }}
          </el-button>

          <!-- 注册链接 -->
          <div class="register-link">
            <span>还没有账号？</span>
            <el-link type="primary" class="register-text" @click="router.push('/register')">
              立即注册
            </el-link>
          </div>

          <!-- 快速登录选项 -->
          <div v-if="isDev" class="quick-login">
            <p class="quick-login-title">快速登录</p>
            <div class="account-list">
              <div class="account-item" @click="setLoginCredentials('root', '123456')">
                <el-avatar icon="UserFilled" size="small" />
                <span>超级管理员</span>
              </div>
              <div class="account-item" @click="setLoginCredentials('admin', '123456')">
                <el-avatar icon="User" size="small" />
                <span>系统管理员</span>
              </div>
              <div class="account-item" @click="setLoginCredentials('test', '123456')">
                <el-avatar icon="Avatar" size="small" />
                <span>测试账号</span>
              </div>
            </div>
          </div>

          <!-- 第三方登录 -->
          <div class="third-party-section">
            <div class="divider">
              <span>其他登录方式</span>
            </div>
            <div class="third-party-login">
              <div class="third-party-icon wechat">
                <div class="i-svg:wechat" />
              </div>
              <div class="third-party-icon qq">
                <div class="i-svg:qq" />
              </div>
              <div class="third-party-icon github">
                <div class="i-svg:github" />
              </div>
              <div class="third-party-icon gitee">
                <div class="i-svg:gitee" />
              </div>
            </div>
          </div>
        </el-form>
      </div>
    </div>

    <!-- 登录页底部 -->
    <div class="login-footer">
      <p>Copyright © 2021 - {{ new Date().getFullYear() }} youlai.tech All Rights Reserved.</p>
      <p><a href="http://beian.miit.gov.cn/" target="_blank">皖ICP备20006496号-2</a></p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { LocationQuery, useRoute } from "vue-router";
import { useI18n } from "vue-i18n";

import AuthAPI, { type LoginFormData } from "@/api/auth";
import router from "@/router";

import type { FormInstance } from "element-plus";

import defaultSettings from "@/settings";
import { ThemeEnum } from "@/enums/ThemeEnum";

import { useSettingsStore, useUserStore, useDictStore } from "@/store";

const userStore = useUserStore();
const settingsStore = useSettingsStore();
const dictStore = useDictStore();

const route = useRoute();
const { t } = useI18n();
const loginFormRef = ref<FormInstance>();

const isDark = ref(settingsStore.theme === ThemeEnum.DARK); // 是否暗黑模式
const loading = ref(false); // 按钮 loading 状态
const isCapslock = ref(false); // 是否大写锁定
const captchaBase64 = ref(); // 验证码图片Base64字符串

// 判断是否为开发环境
const isDev = computed(() => import.meta.env.DEV);
const loginFormData = ref<LoginFormData>({
  username: isDev ? "" : "",
  password: isDev ? "" : "",
  captchaKey: "",
  captchaCode: "",
});

const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.username.required"),
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.password.required"),
      },
      {
        min: 6,
        message: t("login.message.password.min"),
        trigger: "blur",
      },
    ],
    captchaCode: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.captchaCode.required"),
      },
    ],
  };
});

// 获取验证码
function getCaptcha() {
  AuthAPI.getCaptcha().then((data) => {
    loginFormData.value.captchaKey = data.captchaKey;
    captchaBase64.value = data.captchaBase64;
  });
}

// 登录
async function handleLoginSubmit() {
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userStore
        .login(loginFormData.value)
        .then(async () => {
          await userStore.getUserInfo();
          // 需要在路由跳转前加载字典数据，否则会出现字典数据未加载完成导致页面渲染异常
          await dictStore.loadDictionaries();
          // 跳转到登录前的页面
          // const { path, queryParams } = parseRedirect();
          // await router.push({ path: path, query: queryParams });
          await router.push("/");
        })
        .catch(() => {
          getCaptcha();
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

/**
 * 解析 redirect 字符串 为 path 和  queryParams
 *
 * @returns { path: string, queryParams: Record<string, string> } 解析后的 path 和 queryParams
 */
// function parseRedirect(): {
//   path: string;
//   queryParams: Record<string, string>;
// } {
//   const query: LocationQuery = route.query;
//   const redirect = (query.redirect as string) ?? "/";

//   const url = new URL(redirect, window.location.origin);
//   const path = url.pathname;
//   const queryParams: Record<string, string> = {};

//   url.searchParams.forEach((value, key) => {
//     queryParams[key] = value;
//   });

//   return { path, queryParams };
// }

// 主题切换
const toggleTheme = () => {
  const newTheme = settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK;
  settingsStore.changeTheme(newTheme);
};

// 检查输入大小写
function checkCapslock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState("CapsLock");
  }
}

// 设置登录凭证
const setLoginCredentials = (username: string, password: string) => {
  loginFormData.value.username = username;
  loginFormData.value.password = password;
};

onMounted(() => {
  getCaptcha();
});
</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: url("@/assets/images/loginBgc.jpg") center center;
  background-size: cover;
  position: relative;
  overflow: hidden;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3); // 稍微调淡一点遮罩
    z-index: 0;
  }

  // 登录页头部
  .login-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 40px;
    position: relative;
    z-index: 1;

    .logo-container {
      display: flex;
      align-items: center;

      .logo {
        width: 36px;
        height: 36px;
        margin-right: 10px;
      }

      .site-name {
        font-size: 20px;
        font-weight: 600;
        color: var(--el-text-color-primary);
        margin: 0;
      }
    }

    .header-actions {
      display: flex;
      align-items: center;
      gap: 15px;

      .lang-select {
        margin-left: 5px;
      }
    }
  }

  // 登录页内容
  .login-content {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
    position: relative;
    z-index: 1;

    .login-banner {
      display: none;
      flex: 1;
      max-width: 500px;
      padding: 40px;
      color: #fff;

      @media (min-width: 992px) {
        display: flex;
        flex-direction: column;
        justify-content: center;
      }

      .banner-text {
        h2 {
          font-size: 36px;
          font-weight: 700;
          margin-bottom: 20px;
        }

        p {
          font-size: 18px;
          opacity: 0.9;
        }
      }
    }

    .login-form-container {
      width: 100%;
      max-width: 450px;
      background: rgba(255, 255, 255, 0.9); // 半透明背景
      backdrop-filter: blur(10px); // 背景模糊效果
      border-radius: 12px;
      box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
      overflow: hidden;
      transition: all 0.3s ease;

      .login-form {
        padding: 30px;

        .form-header {
          text-align: center;
          margin-bottom: 30px;

          h2 {
            font-size: 24px;
            font-weight: 600;
            color: var(--el-text-color-primary);
            margin-bottom: 8px;
          }

          .form-subtitle {
            color: var(--el-text-color-secondary);
            font-size: 14px;
          }
        }

        .input-wrapper {
          display: flex;
          align-items: center;
          width: 100%;
          background: var(--el-fill-color-blank);
          border: 1px solid var(--el-border-color);
          border-radius: 8px;
          transition: all 0.3s ease;
          overflow: hidden;

          &:hover,
          &:focus-within {
            border-color: var(--el-color-primary);
            box-shadow: 0 0 0 2px rgba(var(--el-color-primary-rgb), 0.1);
          }

          .el-icon {
            margin: 0 12px;
            font-size: 18px;
            color: var(--el-text-color-secondary);
          }

          &.captcha-wrapper {
            .captcha-container {
              position: relative;
              height: 48px;
              cursor: pointer;
              overflow: hidden;

              .captcha-img {
                height: 100%;
                border-radius: 0;
              }

              .captcha-overlay {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                display: flex;
                align-items: center;
                justify-content: center;
                background: rgba(0, 0, 0, 0.5);
                opacity: 0;
                transition: opacity 0.3s;

                .el-icon {
                  color: #fff;
                  font-size: 20px;
                }
              }

              &:hover .captcha-overlay {
                opacity: 1;
              }
            }
          }
        }

        .form-options {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin: 20px 0;

          .forget-link {
            font-size: 14px;
          }
        }

        .login-button {
          width: 100%;
          height: 48px;
          border-radius: 8px;
          font-size: 16px;
          font-weight: 500;
          margin-top: 10px;
          transition: all 0.3s ease;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(var(--el-color-primary-rgb), 0.3);
          }
        }

        .register-link {
          display: flex;
          justify-content: center;
          align-items: center;
          margin: 20px 0;
          padding: 10px;
          font-size: 14px;
          position: relative;

          &::before {
            content: "";
            position: absolute;
            top: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 50px;
            height: 1px;
            background: var(--el-border-color-lighter);
          }

          span {
            color: var(--el-text-color-secondary);
            margin-right: 5px;
          }

          .register-text {
            font-weight: 500;
            transition: all 0.3s ease;

            &:hover {
              transform: translateY(-1px);
              text-decoration: underline;
            }
          }
        }

        .quick-login {
          margin: 25px 0;

          .quick-login-title {
            text-align: center;
            font-size: 14px;
            color: var(--el-text-color-secondary);
            margin-bottom: 15px;
            position: relative;

            &::before,
            &::after {
              content: "";
              position: absolute;
              top: 50%;
              width: 60px;
              height: 1px;
              background: var(--el-border-color);
            }

            &::before {
              left: 50px;
            }

            &::after {
              right: 50px;
            }
          }

          .account-list {
            display: flex;
            justify-content: space-around;

            .account-item {
              display: flex;
              flex-direction: column;
              align-items: center;
              gap: 8px;
              cursor: pointer;
              padding: 10px;
              border-radius: 8px;
              transition: all 0.3s;

              span {
                font-size: 12px;
                color: var(--el-text-color-secondary);
              }

              &:hover {
                background: var(--el-fill-color-light);

                span {
                  color: var(--el-color-primary);
                }
              }
            }
          }
        }

        .third-party-section {
          margin-top: 20px;

          .divider {
            display: flex;
            align-items: center;
            margin: 20px 0;

            &::before,
            &::after {
              content: "";
              flex: 1;
              height: 1px;
              background: var(--el-border-color);
            }

            span {
              padding: 0 15px;
              font-size: 14px;
              color: var(--el-text-color-secondary);
            }
          }

          .third-party-login {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 15px;

            .third-party-icon {
              width: 40px;
              height: 40px;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              cursor: pointer;
              transition: all 0.3s;
              background: var(--el-fill-color-light);

              &:hover {
                transform: translateY(-3px);
              }

              &.wechat:hover {
                background: #07c160;
                color: #fff;
              }

              &.qq:hover {
                background: #12b7f5;
                color: #fff;
              }

              &.github:hover {
                background: #24292e;
                color: #fff;
              }

              &.gitee:hover {
                background: #c71d23;
                color: #fff;
              }
            }
          }
        }
      }
    }
  }

  // 登录页底部
  .login-footer {
    padding: 15px 0;
    text-align: center;
    font-size: 14px;
    color: var(--el-text-color-secondary);
    position: relative;
    z-index: 1;

    p {
      margin: 5px 0;
    }

    a {
      color: var(--el-text-color-secondary);
      text-decoration: none;
      transition: color 0.3s;

      &:hover {
        color: var(--el-color-primary);
      }
    }
  }
}

// 输入框样式覆盖
:deep(.el-form-item) {
  margin-bottom: 20px;
  border: none;
  background: transparent;
}

:deep(.el-input) {
  height: 48px;

  .el-input__wrapper {
    background-color: transparent;
    box-shadow: none !important;
    padding: 0 15px 0 0;

    input {
      height: 48px;
      color: var(--el-text-color-primary);

      &::placeholder {
        color: var(--el-text-color-placeholder);
      }
    }
  }
}

// 暗黑模式适配
html.dark {
  .login-container {
    &::before {
      background: rgba(0, 0, 0, 0.6); // 暗色模式下遮罩更深
    }

    .login-form-container {
      background: rgba(30, 30, 30, 0.8);
      backdrop-filter: blur(10px);
      border: 1px solid rgba(255, 255, 255, 0.1);
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .login-container {
    .login-header {
      padding: 15px 20px;

      .logo-container {
        .logo {
          width: 30px;
          height: 30px;
        }

        .site-name {
          font-size: 18px;
        }
      }
    }

    .login-content {
      padding: 10px;

      .login-form-container {
        max-width: 100%;

        .login-form {
          padding: 20px;

          .form-header {
            margin-bottom: 20px;

            h2 {
              font-size: 20px;
            }
          }
        }
      }
    }
  }
}
</style>
